package y23.Dec;

import java.util.Scanner;

public class Test1 {
    //力扣14：https://leetcode.cn/problems/longest-common-prefix/
    public static void main(String[] args) {
        String[] strings = {"ab","a"};
        System.out.println(new Test1().longestCommonPrefix(strings));
    }

    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 1){
            return strs[0];
        }
        StringBuffer str = new StringBuffer(strs[0]);
        int l = str.length() <= strs[1].length() ? str.length() : strs[1].length();
        for (int i = 1; i < strs.length; i++) {
            if(strs[i].equals("")){
                return strs[i];
            }
            StringBuffer s = new StringBuffer();
            for (int j = 0; j < l; j++) {
                if (str.charAt(j) == strs[i].charAt(j)){
                    s.append(str.charAt(j));
                }else {
                    break;
                }
            }
            if (s.equals("")){
                break;
            }else {
                str = s;
                l = str.length() >= strs[i].length() ? str.length() : strs[i].length();
            }
        }
        return str.toString();
    }
}
